package com.ruoyi.system.controlle;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.system.domain.FileData;
import com.ruoyi.system.domain.FileDataLog;
import com.ruoyi.system.domain.Video;
import com.ruoyi.system.domain.VideoVm;
import com.ruoyi.system.service.VideoService;
import com.ruoyi.system.service.fileDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *描述 ：预案展示
 *@author senyuan.li
 *@date 19:23 2024/3/31
 *@param 
 *@return 
 **/
@Controller
@RequestMapping("/video")
public class VideoController extends BaseController
{

    @Autowired
    private VideoService videoService;



    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(@RequestBody VideoVm video)
    {
        startPage(video.getPageNum(),video.getPageSize());
        List<Video> list = videoService.selectFileDataList(video);
        return getDataTable(list);
    }



    /**
     * @param path 想要下载的文件的路径
     * @param response
     * @功能描述 下载文件:
     */
    @RequestMapping("/download")
    public void download(String fileUrl, HttpServletResponse response) {
        try {
// path是指想要下载的文件的路径
            File file = new File(fileUrl);
            /*log.info(file.getPath());*/
// 获取文件名
            String filename = file.getName();
// 获取文件后缀名
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
            /* log.info("文件后缀名：" + ext);*/

// 将文件写入输入流
            FileInputStream fileInputStream = new FileInputStream(file);
            InputStream fis = new BufferedInputStream(fileInputStream);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();

// 清空response
            response.reset();
// 设置response的Header
            response.setCharacterEncoding("UTF-8");
//Content-Disposition的作用：告知浏览器以何种方式显示响应返回的文件，用浏览器打开还是以附件的形式下载到本地保存
//attachment表示以附件方式下载 inline表示在线打开 "Content-Disposition: inline; filename=文件名.mp3"
// filename表示文件的默认名称，因为网络传输只支持URL编码的相关支付，因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
// 告知浏览器文件的大小
            response.addHeader("Content-Length", "" + file.length());
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            outputStream.write(buffer);
            outputStream.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }


    @PostMapping("/upload")
    @ResponseBody
    public Map upload(MultipartFile file) throws IOException {
        //把文件内容存储到本地磁盘

        //获取文件原始的名称
        String originalFilename = file.getOriginalFilename();

        //把文件内容存储到本地磁盘
        LocalDateTime now = LocalDateTime.now();
        Video filedata=videoService.getfileNameObj(originalFilename);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
        String formattedDateTime = now.format(formatter);
        System.out.println(formattedDateTime);
        if(filedata!=null){
            int lastIndex = originalFilename.lastIndexOf(".");
            String result = originalFilename.substring(0, lastIndex);
            String result2 = originalFilename.substring(lastIndex, originalFilename.length()-1);
            originalFilename=result+formattedDateTime+result2;
        }


        //file.transferTo的异常直接抛出去
        //再次存储的时候使用原来的文件名
        file.transferTo(new File("D:\\user\\"+originalFilename));
        FileData fileData=new FileData();
        fileData.setFileName(originalFilename);
        fileData.setFileUrl("D:\\user\\"+originalFilename);
        Map map=new HashMap();
        map.put("filePath","D:\\user\\"+originalFilename);

        return map;
    }

    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@RequestBody Video video)
    {
        video.setCreateTime(new Date());
        return toAjax(videoService.insertFileData(video));

    }

    @GetMapping("/remove")
    @ResponseBody
    public AjaxResult remove( Integer id)
    {

        return toAjax(videoService.deleteUserByIds(id));
    }

}